/*
 * Copyright (c) 2016 zhangcm. All Rights Reserved.
 */
package com.jnzc.ocr.dependencies.serv.mybatis;

import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jnzc.ocr.common.bean.PageResult;
import com.jnzc.ocr.common.utils.BusinessUtils;
import com.jnzc.ocr.dependencies.serv.bean.BaseFilter;
import com.jnzc.ocr.dependencies.serv.utils.MybatisUtils;
import org.apache.commons.collections4.CollectionUtils;

import java.util.List;

/**
 * @author zhangcm
 * @version 1.0, 2017/10/1
 */
public abstract class MybatisServiceImpl<M extends BaseMapper<T>, T, F extends BaseFilter> extends ServiceImpl<M, T> implements MybatisService<T, F> {

    @Override
    public T find(F filter) {
        EntityWrapper<T> ew = createEntityWrapper(filter);
        return super.selectOne(ew);
    }

    @Override
    public T findNotNull(F filter) {
        EntityWrapper<T> ew = createEntityWrapper(filter);
        T obj = super.selectOne(ew);
        BusinessUtils.notNull(obj, "对象信息不存在");
        return obj;
    }

    @Override
    public PageResult<T> search(F filter, Integer pageNo, Integer pageSize) {
        Pagination pagination = MybatisUtils.createPagination(pageNo, pageSize);
        EntityWrapper<T> ew = createEntityWrapper(filter);
        return MybatisUtils.createPageResult(baseMapper.selectPage(pagination, ew), pagination);
    }

    @Override
    public List<T> list(F filter) {
        EntityWrapper<T> ew = createEntityWrapper(filter);
        return baseMapper.selectList(ew);
    }

    @Override
    public T save(T obj) {
        super.insertOrUpdateAllColumn(obj);
        return obj;
    }

    @Override
    public void saveList(List<T> list) {
        super.insertOrUpdateAllColumnBatch(list);
    }

    @Override
    public void insertOne(T obj) {
        super.insert(obj);
    }

    @Override
    public void insertList(List<T> list) {
        if(CollectionUtils.isEmpty(list)){
            return;
        }
        super.insertBatch(list);
    }

    @Override
    public void updateOne(T obj) {
        super.updateAllColumnById(obj);
    }

    @Override
    public void updateList(List<T> list) {
        if(CollectionUtils.isEmpty(list)){
            return;
        }
        super.updateAllColumnBatchById(list);
    }

    @Override
    public void delete(F filter) {
        EntityWrapper<T> ew = createEntityWrapper(filter);
        super.delete(ew);
    }

    private EntityWrapper<T> createEntityWrapper(F filter) {
        EntityWrapper<T> ew = MybatisUtils.createEntityWrapper(null, filter);
        fillEntityWrapper(ew, filter);
        return ew;
    }

    protected abstract void fillEntityWrapper(EntityWrapper<T> ew, F filter);
}
